from robomaster import robot
import subprocess
import itertools
flvUav= 'rtmp://localhost:1935/live/uav'
fps = 30  # 帧率
width = 960  # 宽度
height = 720  # 高度
# 启动 ffmpeg 进程
ffmpeg_cmd = [
    'ffmpeg',
    '-y',  # 覆盖输出文件而不提示
    '-f', 'rawvideo', # 输入文件格式为原始视频
    '-vcodec', 'rawvideo',
    '-pix_fmt', 'bgr24',   # 像素格式为BGR 24位
    '-s', f'{width}x{height}',
    '-r', str(fps),
    '-i', '-',    # 从标准输入读取帧
    '-c:v', 'libx264',  # 使用libx264编码器
    '-preset', 'ultrafast',  # 编码器预设为ultrafast
    '-f', 'flv',  # 输出格式为FLV
    flvUav
]
# 使用 subprocess.Popen 创建 ffmpeg 进程，并将 stdin 管道化
ffmpeg_process = subprocess.Popen(ffmpeg_cmd, stdin=subprocess.PIPE)
if __name__ == '__main__':
    tl_drone = robot.Drone()
    tl_drone.initialize(conn_type='sta')
    tl_camera = tl_drone.camera
    tl_camera.start_video_stream(display=False)
    tl_camera.set_fps("high")
    tl_camera.set_resolution("high")
    tl_camera.set_bitrate(3)
    for i in itertools.count():
                               try:
                                   img = tl_camera.read_video_frame(timeout=3, strategy='newest')
                                   # 将帧写入 ffmpeg 进程
                                   ffmpeg_process.stdin.write(img)
                               except Exception as e:
                                           print('uavPush error')
                                           tl_camera.stop_video_stream()
                                           ffmpeg_process.stdin.close()
                                           ffmpeg_process.wait()
                                           tl_drone.close()
                                           break  # 使用 break 退出循环
        
        

        

        

